<!--入库列表页面-->
<template>
  <div class="app-container">
    <el-form
      ref="form"
      inline
      :model="form"
      class="form-options"
      label-width="100px"
    >
      <el-form-item label="产品类型">
        <!--fishSpecies 用的是鱼品类型，实际应该是产品类型-->
        <el-autocomplete
          ref="fishSpeciesRef"
          v-model="form.fishSpecies"
          placeholder="请选择产品类型"
          value-key="name"
          :fetch-suggestions="querySearchPurchaseNo"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectPurchaseNo"
          @clear="clickClearfishSpecies"
        />
      </el-form-item>

      <!--需要后台接口获取用户名称等信息-->
      <el-form-item label="质检员">
        <el-autocomplete
          ref="qcNameRef"
          v-model="form.qcName"
          placeholder="请选择质检员"
          value-key="userName"
          :fetch-suggestions="querySysUser"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectSysUser"
          @clear="clickClearqcNameRef"
        />
      </el-form-item>

      <el-form-item label="操作员">
        <el-autocomplete
          ref="inNameRef"
          v-model="form.inName"
          placeholder="请选择操作员"
          value-key="userName"
          :fetch-suggestions="querySysUser"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectInName"
          @clear="clickClearinNameRef"
        />
      </el-form-item>

      <el-form-item label="批次号">
        <el-autocomplete
          ref="batchNoRef"
          v-model="form.batchNo"
          placeholder="请选择批次号"
          value-key="name"
          :fetch-suggestions="querySearchBatchNo"
          :trigger-on-focus="false"
          clearable
          @select="handleSelectBatchNo"
          @clear="clickClearbatchNoRef"
        />
      </el-form-item>

      <el-form-item label="鱼塘">
        <el-autocomplete
          ref="fishpondNameRef"
          v-model="form.fishpondName"
          placeholder="请选择鱼塘"
          value-key="name"
          :fetch-suggestions="querySearchFishpondName"
          :trigger-on-focus="true"
          clearable
          @select="handleSelectFishpondName"
          @clear="clickClearfishpondNameRef"
        />
      </el-form-item>

      <el-form-item label="入库时间" class="long-content">
        <el-date-picker
          v-model="form.date"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          align="right"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="生产日期" class="long-content">
        <el-date-picker
          v-model="form.productionDate"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          align="right"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item label="过期日期" class="long-content">
        <el-date-picker
          v-model="form.expirationDate"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          align="right"
        >
        </el-date-picker>
      </el-form-item>

      <div class="btns">
        <el-button type="primary" @click="onQuery">查询</el-button>
      </div>
    </el-form>

    <!--列表-->
    <el-table
      :data="tableData"
      header-cell-class-name="table-header"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column label="序号" type="index" width="50"> </el-table-column>
      <el-table-column prop="equipmentId" label="唯一编码"> </el-table-column>
      <el-table-column prop="batchNo" label="批次号"> </el-table-column>
      <el-table-column prop="inTime" label="入库时间"> </el-table-column>
      <el-table-column prop="fishSpecies" label="产品类型"> </el-table-column>
      <el-table-column prop="fishpondName" label="鱼塘名称"> </el-table-column>
      <el-table-column prop="inNum" label="入库数量(KG)"> </el-table-column>
      <el-table-column prop="productionDate" label="生产日期">
      </el-table-column>
      <el-table-column prop="expirationDate" label="过期日期">
      </el-table-column>
      <el-table-column prop="qcName" label="质检员"> </el-table-column>
      <el-table-column prop="inName" label="操作员"> </el-table-column>

      <el-table-column label="操作" width="220px">
        <template slot-scope="scope">
          <el-button
            type="primary"
            v-permission="['in_inManage_edit']"
            @click="handleOperateClick(scope.row, '修改')"
            >修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div style="text-align: right; margin-top: 15px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      title="入库修改"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="700px"
    >
      <WarehouseInComponent
        @onSave="onSave"
        :is-only-read="isOnlyRead"
        :mark="0"
        @onSubmit="onSubmit"
        :form="dataForm"
        ref="WarehouseInComponent"
      />
      <span slot="footer">
        <el-button type="primary" v-if="!isOnlyRead" @click="saveData()"
          >保存</el-button
        >
        <!--<el-button type="primary" v-if="!isOnlyRead" @click="submitData()">保存并提交</el-button>-->
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserCondition,
  querySearchFishpondName,
  getFishTypeList,
} from "@/api/common";
import WarehouseInComponent from "../../components/WarehouseInComponent";
import { getIdsFromTreeData, setTreeDisable } from "@/utils/public";
import {
  getBaseEquipmentType,
  getWarehouseInList,
  delWarehouseIn,
  getBatchNos,
} from "@/api/warehouse";

export default {
  name: "WarehouseIn",
  components: {
    WarehouseInComponent,
  },
  data() {
    return {
      currentPage: 1,
      total: 0,
      pageSize: 10,
      form: {
        date: "", //入库日期
        inTimeStart: "",
        inTimeEnd: "",
        productionDate: "", //生产日期
        productionDateStartTime: "",
        productionDateEndTime: "",
        expirationDate: "", //过期日期
        expirationDateStartTime: "",
        expirationDateEndTime: "",
        fishpondName: "", //鱼塘
        qcName: "", //质检员
        inName: "", //操作员
        // inNameId:'',//操作员
        batchNo: "",
      },
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      loading: false,
      tableData: [],
      dialogVisible: false,
      purchaseOptions: [],
      statusOptions: [],
      isOnlyRead: false,
      dataForm: {},
      warehouseOptions: [],
      sysUsers: [],
      fishpond: [],
      sysFishs: [],
    };
  },
  created() {
    getUserCondition({}).then((res) => {
      this.sysUsers = res.resultData;
    });

    querySearchFishpondName({}).then((res) => {
      this.fishpond = res.resultData;
    });

    this.getFishTypeListFun();

    this.onQuery();
  },
  methods: {
    handleSizeChange: function (val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getTableData();
    },
    handleCurrentChange: function (val) {
      this.currentPage = val;
      this.getTableData();
    },
    // 接口-鱼品下拉
    getFishTypeListFun() {
      getFishTypeList({ remark: 1 }).then((res) => {
        this.sysFishs = res.resultData;
      });
    },

    //获取鱼品类型
    querySearchPurchaseNo: function (queryString, cb) {
      const r = this.sysFishs;
      // const r = [{"name":"黑鱼"},{"name":"黑鱼鱼片"},{"name":"鲈鱼"}]  //TODO lihuaibei 后台返回，确保系统一致，好修改
      // console.log(JSON.stringify(r)+"********************************");
      var rs = queryString ? r.filter(this.createFilter(queryString)) : r;
      cb(rs);
    },
    handleSelectPurchaseNo(item) {
      this.form.fishSpecies = item.name;
    },
    clickClearfishSpecies() {
      this.$nextTick(() => {
        if (this.$refs.fishSpeciesRef) {
          this.$refs.fishSpeciesRef.activated = true;
        }
      });
    },
    clickClearqcNameRef() {
      this.$nextTick(() => {
        if (this.$refs.qcNameRef) {
          this.$refs.qcNameRef.activated = true;
        }
      });
    },
    clickClearinNameRef() {
      this.$nextTick(() => {
        if (this.$refs.inNameRef) {
          this.$refs.inNameRef.activated = true;
        }
      });
    },
    clickClearbatchNoRef() {
      this.$nextTick(() => {
        if (this.$refs.batchNoRef) {
          this.$refs.batchNoRef.activated = true;
        }
      });
    },
    clickClearfishpondNameRef() {
      this.$nextTick(() => {
        if (this.$refs.fishpondName) {
          this.$refs.fishpondName.activated = true;
        }
      });
    },

    //获取用户信息
    querySysUser: function (queryString, cb) {
      const r = this.sysUsers;
      // console.log(JSON.stringify(r)+"********************************");
      var rs = queryString
        ? r.filter(this.createFilterUserName(queryString))
        : r;
      cb(rs);
    },
    handleSelectSysUser(item) {
      this.form.qcName = item.userName;
    },

    //操作人员
    handleSelectInName(item) {
      this.form.inName = item.userName;
      // this.form.inNameId= item.id
    },

    //实时从后台查询需要等待，要用同步
    querySearchBatchNo: async function (queryString, cb) {
      let r = [];
      await getBatchNos({ name: queryString }).then((res) => {
        r = res.resultData;
      });
      cb(r);
    },
    handleSelectBatchNo(item) {
      this.form.BatchNo = item.value;
    },

    querySearchFishpondName: function (queryString, cb) {
      const r = this.fishpond;
      var rs = queryString ? r.filter(this.createFilter(queryString)) : r;
      cb(rs);
    },
    handleSelectFishpondName(item) {
      this.form.fishpondName = item.name;
    },

    //模糊建议公共方法
    createFilter(queryString) {
      return (rr) => {
        return rr.name.toLowerCase().indexOf(queryString.toLowerCase()) != -1;
      };
    },
    createFilterUserName(queryString) {
      return (rr) => {
        return (
          rr.userName.toLowerCase().indexOf(queryString.toLowerCase()) != -1
        );
      };
    },

    //查询入库列表数据
    getTableData() {
      if (this.form.date && this.form.date[0]) {
        this.form.inTimeStart = this.form.date[0];
      } else {
        this.form.inTimeStart = "";
      }
      if (this.form.date && this.form.date[1]) {
        this.form.inTimeEnd = this.form.date[1];
      } else {
        this.form.inTimeEnd = "";
      }

      if (this.form.productionDate && this.form.productionDate[0]) {
        this.form.productionDateStartTime = this.form.productionDate[0];
      } else {
        this.form.productionDateStartTime = "";
      }
      if (this.form.productionDate && this.form.productionDate[1]) {
        this.form.productionDateEndTime = this.form.productionDate[1];
      } else {
        this.form.productionDateEndTime = "";
      }

      if (this.form.expirationDate && this.form.expirationDate[0]) {
        this.form.expirationDateStartTime = this.form.expirationDate[0];
      } else {
        this.form.expirationDateStartTime = "";
      }
      if (this.form.expirationDate && this.form.expirationDate[1]) {
        this.form.expirationDateEndTime = this.form.expirationDate[1];
      } else {
        this.form.expirationDateEndTime = "";
      }

      const param = { page: this.currentPage, rows: this.pageSize };

      Object.assign(param, this.form);
      getWarehouseInList(param).then((res) => {
        this.tableData = res.resultData;
        this.total = res.total;
      });
    },
    handleOperateClick(row, tag) {
      if (tag == "删除") {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        }).then(() => {
          delWarehouseIn({ id: row.id }).then((res) => {
            this.onQuery();
          });
        });
      } else if (tag == "查看") {
        this.queryDetail(row.id, true);
      } else if (tag == "修改") {
        this.queryDetail(row.id, false);
      }
    },
    queryDetail(id, isReadOnly) {
      const param = { page: 1, rows: 1, id: id };
      const a = new Promise((resolve) => {
        getBaseEquipmentType({}).then((res) => {
          resolve(res.resultData);
        });
      });

      const b = new Promise((resolve) => {
        getWarehouseInList(param).then((res) => {
          resolve(res.resultData[0]);
        });
      });

      Promise.all([a, b]).then((res) => {
        const data = res[1];
        this.dataForm = {
          id: data.id,
          busInDetailsId: data.busInDetailsId,
          equipmentId: data.equipmentId,
          batchNo: data.batchNo,
          inTime: data.inTime,
          fishSpecies: data.fishSpecies,
          fishpondName: data.fishpondName,
          productionDate: data.productionDate,
          expirationDate: data.expirationDate,
          qcName: data.qcName,
          inNum: data.inNum,
          inName: data.inName,
        };

        this.isOnlyRead = isReadOnly;
        this.dialogVisible = true;
      });
    },

    // --------------------分割--------------------

    handleSelectOperName(item) {
      this.form.operName = item.value;
    },
    handleSelectPurchaseName(item) {
      this.form.purchaseName = item.value;
    },

    saveData() {
      this.$refs["WarehouseInComponent"].save();
    },
    onSave() {
      this.dialogVisible = false;
      this.onQuery();
    },
    submitData() {
      this.$refs["WarehouseInComponent"].saveAndSubmit();
    },
    onSubmit() {
      this.dialogVisible = false;
      this.onQuery();
    },
    onQuery() {
      this.currentPage = 1;
      this.getTableData();
    },
    onAdd() {
      this.$alert("请在批次管理中新增入库", "温馨提示", {
        confirmButtonText: "确定",
        callback: (action) => {},
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}
</style>
